package com.tools.service.workflow.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tools.mapper.workflow.StepDefinitionMapper;
import com.tools.pojo.workflow.po.StepDefinition;
import com.tools.service.workflow.StepDefinitionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class StepDefinitionServiceImpl extends ServiceImpl<StepDefinitionMapper, StepDefinition> implements StepDefinitionService {

    private final ObjectMapper objectMapper;

    /**
     * 根据步骤编码获取步骤定义
     */
    @Override
    public StepDefinition getByCode(String stepCode) {
        return lambdaQuery()
                .eq(StepDefinition::getStepCode, stepCode)
                .one();
    }

    /**
     * 获取所有步骤定义
     */
    @Override
    public List<StepDefinition> getAllStepDefinitions() {
        return lambdaQuery().list();
    }

    /**
     * 根据步骤类型获取步骤定义
     */
    @Override
    public List<StepDefinition> getByStepType(String stepType) {
        return lambdaQuery()
                .eq(StepDefinition::getStepType, stepType)
                .list();
    }

    /**
     * 解析步骤配置
     */
    @Override
    public Map<String, Object> parseStepConfig(String configJson) {
        try {
            if (configJson == null || configJson.trim().isEmpty()) {
                return Map.of();
            }
            return objectMapper.readValue(configJson, new TypeReference<>() {
            });
        } catch (Exception e) {
            log.error("解析步骤配置失败", e);
            return Map.of();
        }
    }

    /**
     * 创建步骤定义
     */
    public boolean createStepDefinition(StepDefinition stepDefinition) {
        // 检查步骤编码是否已存在
        StepDefinition existing = getByCode(stepDefinition.getStepCode());
        if (existing != null) {
            throw new RuntimeException("步骤编码已存在: " + stepDefinition.getStepCode());
        }
        return save(stepDefinition);
    }

}
